import { Overlay, OverlayConfig, OverlayRef } from '@angular/cdk/overlay';
import { ComponentPortal } from '@angular/cdk/portal';
import { ComponentRef, Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
import { CaptchaComponent } from './captcha.component';

@Injectable({
  providedIn: 'root',
})
export class DunHelper {
  captchacontainerRef!: ComponentRef<CaptchaComponent>;
  userInfo;

  constructor(private overlay: Overlay) {
    this.userInfo = JSON.parse(localStorage.getItem('user') || '{}');
  }

  /**
   * 组件初始化
   * @param phone  手机号
   * @param url 发送验证码请求地址
   */
  init(phone: string, url?: string): Subject<any> {
    const overlayRef = this.createOverlay();
    const containerPortal = new ComponentPortal(CaptchaComponent);
    this.captchacontainerRef = overlayRef.attach<CaptchaComponent>(containerPortal);
    this.captchacontainerRef.instance.phone = phone;
    this.captchacontainerRef.instance.url = url || '';
    return this.captchacontainerRef.instance.init();
  }

  /**
   * 弹出滑块验证
   * @param phone 手机号
   * @param url 发送验证码请求地址
   */
  popUp(phone?: string, url?: string): Observable<any> {
    if (this.captchacontainerRef) {
      this.destory();
    }

    this.init(phone || this.userInfo?.phone, url).subscribe((instance) => {
      if (instance) {
        this.captchacontainerRef.instance.popUp();
      }
    });

    /*  if (!this.captchacontainerRef) {
             this.init(phone || this.userInfo?.phone, url).subscribe(instance => {
                 if (instance) {
                     this.captchacontainerRef.instance.popUp();
                 }
             });
         } else {
             if (!!phone && !!url) {
                 this.init(phone || this.userInfo?.phone, url).subscribe(instance => {
                     if (instance) {
                         this.captchacontainerRef.instance.popUp();
                     }
                 });
             } else {
                 this.captchacontainerRef.instance.popUp();
             }
         } */
    return this.captchacontainerRef.instance.done;
  }

  /** 组件销毁 */
  destory() {
    this.captchacontainerRef.destroy();
  }

  private createOverlay(): OverlayRef {
    const overlayConfig = new OverlayConfig({
      hasBackdrop: false,
      scrollStrategy: this.overlay.scrollStrategies.block(),
      positionStrategy: this.overlay.position().global(),
      backdropClass: 'captcha-back-drop',
      panelClass: 'captcha-overlay',
    });

    return this.overlay.create(overlayConfig);
  }
}
